<template>
  <view class="settings-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <h1 class="page-title">设置</h1>
    </view>

    <!-- 用户信息卡片 -->
    <view class="user-card">
      <!-- 用户头像 -->
      <view class="avatar-container">
        <image 
          :src="userData.imgPath || 'https://picsum.photos/200/200'" 
          class="avatar" 
          mode="aspectFill"
          @click="uploadAvatar"
        ></image>
        <text class="avatar-hint">点击更换头像</text>
      </view>

      <!-- 表单区域 -->
      <form class="user-form">
        <!-- 用户名 -->
        <view class="form-item">
          <text class="item-label">用户名</text>
          <input 
            type="text" 
            class="item-input" 
            v-model="userData.username" 
            placeholder="请输入用户名"
          >
        </view>

        <!-- 密码 -->
        <view class="form-item">
          <text class="item-label">密码</text>
          <input 
            type="password" 
            class="item-input" 
            v-model="userData.password" 
            placeholder="请输入密码"
          >
        </view>

        <!-- 手机号 -->
        <view class="form-item">
          <text class="item-label">手机号</text>
          <input 
            type="tel" 
            class="item-input" 
            v-model="userData.phone" 
            placeholder="请输入手机号"
          >
        </view>
      </form>
    </view>

    <!-- 操作按钮区域 -->
    <view class="action-buttons">
      <button 
        class="cancel-btn" 
        @click="handleCancel"
      >
        取消
      </button>
      <button 
        class="confirm-btn" 
        @click="saveSettings"
      >
        确定
      </button>
    </view>

    <!-- 退出登录按钮 -->
    <view class="logout-container">
      <button 
        class="logout-btn" 
        @click="logout"
      >
        退出登录
      </button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { reactive, toRefs } from 'vue';
import { useUserStore } from '@/stores/api.js';
import dayjs from 'dayjs';

const userStore = useUserStore();

// 表单数据
const userData = reactive({
  username: userStore.getUserName,
  password: '',
  phone: userStore.getPhone,
  imgPath: userStore.getImgPath,
  amendName: userStore.getUserName
});

// 保存原始数据，用于取消操作
const originalData = reactive({
  username: userStore.getUserName,
  password: '',
  phone: userStore.getPhone,
  imgPath: userStore.getImgPath
});

// 检查数据是否被修改
const isDataChanged = () => {
  return (
    userData.username !== originalData.username ||
    userData.phone !== originalData.phone ||
    userData.imgPath !== originalData.imgPath ||
    (userData.password && userData.password !== originalData.password)
  );
};

// 上传头像
const uploadAvatar = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      userData.imgPath = res.tempFilePaths[0];
      // 这里可以添加上传到服务器的逻辑
    }
  });
};

// 处理取消操作
const handleCancel = () => {
  // 如果数据已修改，显示确认对话框
  if (isDataChanged()) {
    uni.showModal({
      title: '确认取消',
      content: '您的修改尚未保存，确定要取消吗？',
      success: (res) => {
        if (res.confirm) {
          cancelEdit();
        }
      }
    });
  } else {
    // 如果数据未修改，直接返回
    uni.navigateBack();
  }
};

// 取消编辑，恢复原始数据
const cancelEdit = () => {
  userData.username = originalData.username;
  userData.phone = originalData.phone;
  userData.imgPath = originalData.imgPath;
  userData.password = ''; // 清空密码
  uni.navigateBack(); // 返回上一页
};

// 保存设置
const saveSettings = () => {
  // 表单验证
  if (!userData.username.trim()) {
    uni.showToast({ title: '用户名不能为空', icon: 'none' });
    return;
  }
  
  if (!userData.phone.trim()) {
    uni.showToast({ title: '手机号不能为空', icon: 'none' });
    return;
  }
  
  // 手机号格式验证
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(userData.phone)) {
    uni.showToast({ title: '手机号格式不正确', icon: 'none' });
    return;
  }
  
  // 准备请求数据
  const requestData = {
    imgPath: userData.imgPath,
    userId: userStore.getUserId,
    username: userData.username,
    phone: userData.phone,
    amendName: userStore.getUserName,
    amendTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
  };
  
  // 如果密码不为空，则添加到请求数据中
  if (userData.password) {
    requestData['password'] = userData.password;
  }
  console.log(requestData)
  // 发送保存请求
  uni.request({
    url: 'http://127.0.0.1:8088/UserAppLogin/update',
    method: 'POST',
    data: requestData,
    header: {
      'Content-Type': 'application/json',
    },
    success: (res) => {
      console.log('保存设置成功:', res.data);
      
      // 处理响应
      if (res.data.code === 200) {
        // 如果更新了密码，清除所有store数据并跳转到登录页
        if (userData.password) {
          userStore.$reset();
          uni.showToast({ 
            title: '密码已修改，请重新登录', 
            icon: 'success',
            duration: 2000
          });
          
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/login'
            });
          }, 2000);
          
          return;
        }
        
        // 更新本地store
        userStore.setUserInfo({
          username: userData.username,
          phone: userData.phone,
          imgPath: userData.imgPath
        });
        
        // 显示成功提示
        uni.showToast({ title: '设置保存成功', icon: 'success' });
        
        // 更新原始数据
        originalData.username = userData.username;
        originalData.phone = userData.phone;
        originalData.imgPath = userData.imgPath;
        
        // 返回上一页
        uni.navigateBack();
      } else {
        uni.showToast({ 
          title: res.data.message || '保存失败', 
          icon: 'none' 
        });
      }
    },
    fail: (err) => {
      console.error('保存设置失败:', err);
      uni.showToast({ title: '网络错误，保存失败', icon: 'none' });
    }
  });
};

// 退出登录
const logout = () => {
  uni.showModal({
    title: '确认退出',
    content: '您确定要退出当前账号吗？',
    success: (res) => {
      if (res.confirm) {
        // 清除用户信息
        
		userStore.setUserInfo(null)
		
        
        // 返回个人中心页面
        uni.switchTab({
                  url: '/pages/myself/index'
                });
      }
    }
  });
};
</script>

<style>
/* 整体页面样式 */
.settings-page {
  padding: 30rpx;
  background-color: #f5fffa; /* 淡薄荷绿背景 */
  min-height: 100vh;
}

/* 页面标题 */
.page-header {
  margin-bottom: 40rpx;
  text-align: center;
}

.page-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #20b2aa; /* 薄荷绿标题色 */
}

/* 用户卡片 */
.user-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 60rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

/* 头像容器 */
.avatar-container {
  text-align: center;
  margin-bottom: 40rpx;
}

.avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  border: 2rpx solid #20b2aa;
  margin-bottom: 15rpx;
}

.avatar-hint {
  font-size: 24rpx;
  color: #556b2f;
}

/* 表单样式 */
.user-form {
  width: 100%;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #e0f2f1;
}

.item-label {
  width: 200rpx;
  font-size: 30rpx;
  color: #008b8b; /* 深薄荷绿标签 */
}

.item-input {
  flex: 1;
  height: 60rpx;
  font-size: 30rpx;
  color: #333;
  padding-left: 20rpx;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: space-between;
  padding: 0 20rpx;
  margin-bottom: 40rpx;
}

.cancel-btn,
.confirm-btn {
  width: 300rpx;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 500;
}

.cancel-btn {
  background-color: #fff;
  color: #20b2aa;
  border: 2rpx solid #20b2aa;
}

.confirm-btn {
  background-color: #20b2aa;
  color: #fff;
  border: none;
}

/* 退出登录按钮 */
.logout-container {
  padding: 0 30rpx;
}

.logout-btn {
  width: 100%;
  height: 96rpx;
  border-radius: 48rpx;
  background-color: #f8f8f8;
  color: #e74c3c;
  font-size: 34rpx;
  font-weight: 500;
  border: 2rpx solid #e74c3c;
}
</style>